package us.mooresr.aircraftscheduling.client.place;

import com.gwtplatform.mvp.client.proxy.PlaceManagerImpl;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;

import us.mooresr.aircraftscheduling.client.LoginStateManager;
import us.mooresr.aircraftscheduling.client.place.DefaultPlace;

import com.google.inject.Inject;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.gwtplatform.mvp.client.proxy.TokenFormatter;

public class ClientPlaceManager extends PlaceManagerImpl {

	private final PlaceRequest defaultPlaceRequest;
	private final LoginStateManager loginStateManager;

	@Inject
	public ClientPlaceManager(final EventBus eventBus,
			final TokenFormatter tokenFormatter,
			@DefaultPlace final String defaultPlaceNameToken,
			LoginStateManager loginStateManager) {
		super(eventBus, tokenFormatter);
		this.defaultPlaceRequest = new PlaceRequest(defaultPlaceNameToken);
		this.loginStateManager = loginStateManager;

	}

	@Override
	public void revealDefaultPlace() {
		revealPlace(defaultPlaceRequest, false);
	}
	
	@Override
	public void revealErrorPlace(String invalidHistoryToken) {
		GWT.log("Got bad historty token " + invalidHistoryToken);
		PlaceRequest errorPlaceRequest;
		
		if (loginStateManager.isLoggedIn()) {
			// User is logged in, must just be a bad token
			GWT.log("User is logged in, redirecting to reservation list");
			errorPlaceRequest = new PlaceRequest(NameTokens.reservationlist);
		} else {
			// User is not logged in, so this is probably a Gatekeeper error.
			errorPlaceRequest = new PlaceRequest(NameTokens.login);
		}
		revealPlace(errorPlaceRequest, false);
	}
}
